app.config( function($routeProvider){
	$routeProvider
	  .when('/',
		{
		  templateUrl: APP_PATH + '/Phone/login_welcome',
		  controller: 'WelcomeCtrl'
		})
	  .when('/qrcode',{
			templateUrl: APP_PATH  + '/Phone/login_qrcode',
			controller: 'QRcodeCtrl'
	  })	
	  .when('/view',{
			templateUrl: APP_PATH  + '/Phone/view_info',
			controller: 'ViewCtrl'
	  })	
	  .when('/search',{
			templateUrl: APP_PATH  + '/Phone/search',
			controller: 'SearchCtrl'
	  })
	  .when('/confirm',{
			templateUrl: APP_PATH  + '/Phone/confirm',
			controller: 'ConfirmCtrl'
	  })
	  .when('/pay',{
			templateUrl: APP_PATH  + '/Phone/pay',
			controller: 'SearchCtrl'
	  })
	  .when('/load',{
			templateUrl: APP_PATH  + '/Phone/load',
			controller: 'LoadCtrl'
	  })	  
	  .otherwise({
		redirectTo: function(routeParams,path,search){
		  console.log("未定义的路由");
		  console.log(routeParams);
		  console.log(path);
		  console.log(search);
		}
	  });	
} )
.factory('is_weixin', function(){
	return function() {
		var pattern = /MicroMessenger/i;
		return pattern.test(navigator.userAgent);
	}
})
.controller("AppCtrl",function($rootScope,$scope,$timeout,$route,$location,$http,is_weixin){
	//切换路由
	$scope.changeRoute = function(url) {
		$location.path(url);
	};	
	
	$scope.dbSearch = {};
	
	$scope.is_weixin = is_weixin;

	$scope.student = {};
	
	$scope.majors = majors;

	$scope.school_lengths = [];
	
	$scope.majors.forEach( function(o){
		var length = o.school_length.toString().replace('年','');
		if ( $scope.school_lengths.indexOf(length) == -1 ) {
			$scope.school_lengths.push(length);
		}
	} );
	
	$scope.getMajorRow = function( major_id ) {
		for ( var attr in $scope.majors ) {			
			if ( $scope.majors[attr].mid == major_id ) {
				return $scope.majors[attr];
			}
		}
		return '--';
	}
	
	//生成db属性，用于子$scope
	$scope.db = new Db(APP_PATH + '/Phone',$http);
	
	$scope.toastErrorShow = function(html,fn) {
		var toastError = $('#toastError');
		if (toastError.css('display') != 'none') {
			return;
		}
		toastError.find('.weui_cell_bd').html(html);
		toastError.show();
		
		setTimeout(function () {
			toastError.hide();
			if ( fn ) {
				fn();
			}
		}, 2000);		
	}
	
	$scope.loadSearch = function(){
		Zepto( function(){
            $('#container').on('focus', '#search_input', function () {
                var $weuiSearchBar = $('#search_bar');
                $weuiSearchBar.addClass('weui_search_focusing');
            }).on('blur', '#search_input', function () {
                var $weuiSearchBar = $('#search_bar');
                $weuiSearchBar.removeClass('weui_search_focusing');
                if ($(this).val()) {
                    $('#search_text').hide();
					$scope.doSearch();
                } else {
                    $('#search_text').show();
                }
            }).on('input', '#search_input', function () {
                var $searchShow = $("#search_show");
                if ($(this).val()) {
                    $searchShow.show();
                } else {
                    $searchShow.hide();
                }
            }).on('touchend', '#search_cancel', function () {
                $("#search_show").hide();
                $('#search_input').val('');
            }).on('touchend', '#search_clear', function () {
                $("#search_show").hide();
                $('#search_input').val('');
            });
		});
	}
	
	$scope.loadMenu = function(){
		if (  !$scope.student.std_name ) {
			//$scope.changeRoute('/');
		}
		Zepto( function(){
			$('#container').on('click', '#showActionSheet', function () {
				
				var mask = $('#mask');
				var weuiActionsheet = $('#weui_actionsheet');
				weuiActionsheet.addClass('weui_actionsheet_toggle');
				mask.show().addClass('weui_fade_toggle').one('click', function () {
					hideActionSheet(weuiActionsheet, mask);
				});
				$('#actionsheet_cancel').one('click', function () {
					hideActionSheet(weuiActionsheet, mask);
				});
				weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');

				function hideActionSheet(weuiActionsheet, mask) {
					weuiActionsheet.removeClass('weui_actionsheet_toggle');
					mask.removeClass('weui_fade_toggle');
					weuiActionsheet.on('transitionend', function () {
						mask.hide();
					}).on('webkitTransitionEnd', function () {
						mask.hide();
					})
				}
			});	
		} );		
		
	}
	
	$scope.initTool = function( ){
		$scope.loadMenu();
		$scope.loadSearch();
	}
	
	$scope.toRoutePay = function(){
		$scope.menuShow = 0;
		$scope.changeRoute('pay');
	}
	
	$scope.dialogShow = function(on,method) {
		if ( on ) {
			$('.weui_mask').show();
			$('.weui_dialog_alert').show();
			if ( method=='qrcode' ) {
				//更换标题内容
				$('#dialogTitle').html( $scope.student.std_name + '同学的二维码');
				//显示加载图片
				$('#dialogBody').html('<i class="fa fa-spinner fa-spin fa-3x fa-fw margin-bottom"></i>');
				//获取二维码地址（含第一次生成二维码）
				$scope.db.httpGet('getQRcode/std_uid/' + $scope.student.std_uid + '/VAR_AJAX_SUBMIT/1').success(function(res){
					var src = ROOT_PATH + '/Qrcode/' + res;
					$('#dialogBody').html('<img src="' + src + '" style="width:100%;" />');
				} );
			} else if ( method == 'password' ) {
				//更换标题内容
				$('#dialogTitle').html( $scope.student.std_name + '同学的登陆密码');
				//显示加载图片
				$('#dialogBody').html($scope.student.std_pwd);			
			}
		} else {
			$('.weui_mask').hide();
			$('.weui_dialog_alert').hide();			
		}
		
	}	
	
	$scope.doSearch = function( ){
		$scope.db.find('doSearch',{'where':{'std_name':$scope.dbSearch.value,'enter_year':NOW_YEAR}}).success(function( result ){
			$scope.dbSearch.data = result.data;
			$scope.changeRoute('search');
		} );
	}
	
	$scope.view = function( student ) {
		if ( student ){
			$scope.menuShow = 1;
			$scope.student = student;
			$scope.changeRoute('view');
		}
	}
	
	$scope.logout = function() {
		location.href = APP_PATH + '/Index/logout';
	}
	
	$scope.toastSuccessShow = function(html,fn) {
		var toastSuccess = $('#toastSuccess');
		if (toastSuccess.css('display') != 'none') {
			return;
		}
		toastSuccess.find('.weui_cell_bd').html(html);
		toastSuccess.show();
		
		setTimeout(function () {
			toastSuccess.hide();
			if ( fn ) {
				fn();
			}
		}, 2000);		
	}	
	
})
.controller('WelcomeCtrl',function($rootScope,$scope) {
	$scope.initTool();
	$scope.searchShow = true;
})
.controller('SearchCtrl',function($rootScope,$scope) {
	$scope.initTool();
})
.controller('LoadCtrl',function($rootScope,$scope,$location,$timeout) {
	$scope.initTool();
	$scope.btnShow = false;
	var search = $location.search();
	if ( search && search.std_uid) {
		$scope.db.find('find',{'where':{'std_uid':search.std_uid,'enter_year':NOW_YEAR}}).success(function( result ){
			$scope.$parent.student = result.data;
			$('.weui_icon_msg').removeClass('weui_icon_waiting').addClass('weui_icon_success');
			$('.weui_msg_desc').html('加载成功');
			$scope.btnShow = true;			
			if ( result.data.status >= 5 ) {
				$scope.changeRoute('pay');
			}			
			
			if ( result.data.status == 0 ) {
				$timeout( function(){
					$scope.changeRoute('confirm');
				},100 );
				
			}
			
		} );
	}	
	
})
.controller("QRcodeCtrl", function($scope){
	$scope.initTool();
} )
.controller('ViewCtrl',function( $scope ,$location){
	$scope.initTool();	
})
.controller('ConfirmCtrl',function( $scope ,$location){
	$scope.initTool();
	var is_post = false;
	if ( $scope.student && $scope.student.status==0 && !is_post) {
		$scope.db.post('confirm_bell',{'std_uid':$scope.student.std_uid,'status':0,'is_read':0}).success(function( result ){
			$scope.btnShow = true;
			P(result);
			if ( result.status==0 ) {
				$('.weui_icon_msg').removeClass('weui_icon_waiting').addClass('weui_icon_success');
				$('.weui_msg_title').html('通知成功');				
				$('.weui_msg_desc').html(result.info);				
			} else {
				$('.weui_icon_msg').removeClass('weui_icon_waiting').addClass('weui_icon_warn');
				$('.weui_msg_title').html('通知失败');
				$('.weui_msg_desc').html(result.info);						
			}
		} );
	}
})
.controller('PayCtrl',function($rootScope,$scope) {
	$scope.initTool();
	$scope.payShow = 1;
	$scope.paySuccessShow = 0;
	$scope.payErrorShow = 0;
	$scope.doPay = function(student) {
		$scope.db.post('doPay',{'where':{'std_uid':student.std_uid}}).success(function(result){
			if ( result.status === '0' ) {
				$scope.payShow = 0;
				$scope.paySuccessShow = 1;
				$scope.payErrorShow = 0;
				var html = $('#paySuccessDesc').html();
				$scope.student.status = '6';
				$('#paySuccessDesc').html( result.info + html);
			} else {
				$scope.payShow = 0;
				$scope.paySuccessShow = 0;
				$scope.payErrorShow = 1;
				var html = $('#payErrorDesc').html();
				$('#payErrorDesc').html( result.info + html);
			}				
		} );
	}
})
.controller("EditMajorCtrl", function($scope){
	$scope.loadMenu();
	$scope.student.verify = '';
	var ori_major = $scope.student.major_id;
	$scope.submit = function(student) {
		if ( $scope.CtrlForm.$valid ) {
			if ( ori_major == $scope.student.major_id  ) {
				$scope.toastErrorShow('<p>请勿提交相同数据!!</p>');
			} else {
				$scope.db.post('doEdit',student).success(function(result){
					if ( result.status === '0' ) {
						ori_major = $scope.student.major_id;
						$scope.toastSuccessShow(result.info,function() {		
							$('#verifyImg').trigger('click');
						} );
					} else {
						$scope.toastErrorShow(result.info);
					}				
				} );
			}	
		} else {
			$scope.toastErrorShow('<p>有数据未正确填写，不能提交!!</p>');
		}
	}
} )
;